package com.itheima.d7_tcp4;

import java.io.*;
import java.net.InetAddress;
import java.net.Socket;

public class ServerThread implements Runnable{
    private Socket socket;

    public ServerThread(Socket socket) {
        this.socket = socket;
    }

    @Override
    public void run() {
        BufferedReader br = null;
        try {
            InputStream is = socket.getInputStream();
            InputStreamReader isr = new InputStreamReader(is);
            br = new BufferedReader(isr);
            InetAddress ia = socket.getInetAddress();
            while (true) {
                String content = br.readLine();
                if(content == null){
                    Server.list.remove(socket);
                    break;
                }
                System.out.println(ia+ "发送了："+content);

                for (Socket otherSocket : Server.list) {
                    if(otherSocket != socket){
                        BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(otherSocket.getOutputStream()));
                        bw.write(content);
                        bw.newLine();
                        bw.flush();
                    }
                }
            }
        } catch (IOException e) {
            throw new RuntimeException(e);
        } finally {
            try {
                br.close();
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
            try {
                socket.close();
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        }

    }
}
